package NiuKe.PriorityQueue;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class TopK {

    public static int[] topK(int [] array,int k){
        PriorityQueue<Integer> maxHeap=new PriorityQueue<>(k, new Comparator<Integer>() {
            //创建一个大小为K的大根堆
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;//小根堆o1-o2;
            }
        });
        //2,遍历数组当中的元素，前K个元素放到队列中
        for (int i = 0; i < array.length; i++) {
            if (maxHeap.size()<k){
                maxHeap.offer(array[i]);
            }else{
                //3,从k+1个元素开始，每个元素与k顶元素进行比较
                int top=maxHeap.peek();
                if (top>array[i]){
                    //3.1先弹出后进来
                    maxHeap.poll();
                    maxHeap.offer(array[i]);
                }
            }
        }
        int[] tmp=new int[k];
        for (int i = 0; i < k; i++) {
            tmp[i]=maxHeap.poll();
        }
        return tmp;
    }

    public static void main(String[] args) {
        int [] array={18,21,8,10,334,12};
        int [] tmp=topK(array,3);
        System.out.println(Arrays.toString(tmp));
    }




























}
